package com.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.pojo.Manager;
import com.ssm.pojo.Msg;
import com.ssm.pojo.SManager;
import com.ssm.service.ManagerService;
import com.ssm.service.SManagerService;
import com.ssm.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SManagerController {

    @Autowired
    SManagerService sManagerService;
    @Autowired
    StuService stuService;
    @Autowired
    ManagerService managerService;

    @RequestMapping("/showManager")
    public String showManager(Model model) {
        List<Manager> managers = managerService.list();
        model.addAttribute("managers", managers);
        return "smanager/smanagershow";
    }

    @RequestMapping(value = "/showManagers", method = RequestMethod.GET)
    @ResponseBody
    public Msg showManagers(@RequestParam(value = "pn", defaultValue = "1") int pn,
                            @RequestParam(value = "select_value", defaultValue = "1") int value,
                            @RequestParam(required = false) String find_value) {
        /*
         * 在查询之前只需要调用，传入页码。以及每页的大小
         * */
        if (find_value == "undefined") {
            find_value = "";
        }
        PageHelper.startPage(pn, 5);
        if (value == 1) {
            List<Manager> list = managerService.list();
            PageInfo page = new PageInfo(list, 5);
            return Msg.success().add("pageInfo", page).add("selectvalue", value).add("find_v", find_value);
        } else if (value == 2) {
            List<Manager> list = managerService.find_name(find_value);
            PageInfo page = new PageInfo(list);
            return Msg.success().add("pageInfo", page).add("selectvalue", value).add("find_v", find_value);
        } else if (value == 3) {
            List<Manager> list = managerService.find_cdorm(find_value);
            PageInfo page = new PageInfo(list, 5);
            return Msg.success().add("pageInfo", page).add("selectvalue", value).add("find_v", find_value);
        } else {
            return Msg.fail().add("value", value);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/manager", method = RequestMethod.POST)
    public Msg saveManager(@Valid Manager manager, BindingResult result) { //@Valid代表manager的数据要被校验,BindingResult类为封装校验的结果
        if (manager.getId() == null) {
            manager.setId("");
        }
        if (manager.getPhone() == null) {
            manager.setPhone("");
        }
        if (manager.getAddress() == null) {
            manager.setAddress("");
        }
        if (manager.getSdorm() == null) {
            manager.setSdorm("");
        }
        if (result.hasErrors()) {
            Map<String, Object> map = new HashMap<String, Object>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError error : fieldErrors) {
                map.put(error.getField(), error.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);
        } else {
            managerService.addManager(manager);
            return Msg.success();
        }
    }

    //使用字符串的格式获得manager对应数据
    @ResponseBody
    @RequestMapping(value = "/getManager")
    public Msg getManager(String amount) {
        Manager manager = managerService.query(amount);
        return Msg.success().add("manager", manager);
    }

    @ResponseBody
    @RequestMapping(value = "/checkManager", method = RequestMethod.POST)
    public Msg checkManager(String amount) {
        String regAmount = "(^[0-9]{4,14}$)";
        if (!amount.matches(regAmount)) {
            return Msg.fail().add("va_msg", "账号应为4~14位数字");
        }
        Manager i = managerService.query(amount);
        int i1 = i == null ? 0 : 1;
        if (i1 != 1) {
            return Msg.success();
        } else {
            return Msg.fail().add("va_msg", "账号存在");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/managerUpdate", method = RequestMethod.POST)
    public Msg managerUpdate(Manager manager) {
        System.out.println(manager);
        managerService.updateManager(manager);
        return Msg.success();
    }

    @ResponseBody
    @RequestMapping(value = "/managerDel", method = RequestMethod.POST)
    public Msg deleteManager(String amount) {
        List<String> list = new ArrayList<String>();
        if (amount.contains("-")) {
            String[] str_all = amount.split("-");
            for (String str : str_all) {
                list.add(str);
            }
            managerService.deleteManagerList(list);
        } else {
            managerService.deleteManager(amount);
        }
        return Msg.success();

    }

    @PostMapping("/updates_pw")
    @ResponseBody
    public Msg updates(String amount, String password, HttpSession session){
        try {
            sManagerService.update_pw(amount,password);
        } catch (Exception e) {
            return Msg.fail();
        }
        session.setAttribute("manager",sManagerService.findByAmount(amount));
        return Msg.success();
    }

    @GetMapping("/updates")
    @ResponseBody
    public Msg update(SManager sManager, HttpSession session) {
        try {
            sManagerService.update(sManager);
            session.setAttribute("manager",sManagerService.findByAmount(sManager.getAmount()));
        } catch (Exception e) {
            return Msg.fail();
        }
        return Msg.success();
    }
}
